<?php


namespace App\Service;


use App\Jobs\TaskJob;
use App\Models\SiteGold;
use App\Models\UserGold;
use Illuminate\Support\Facades\Config;
use Qiniu\Auth;
use Qiniu\Storage\BucketManager;
use Qiniu\Storage\UploadManager;

class Qiniu
{
    protected $error;

    // 七牛云操作
    public function __construct() { }

    // 获取错误信息
    public function getError()
    {
        return $this->error;
    }

    // 上传图片
    // 上传七牛云
    //  $to    = 'caiji/weixin/'.date('Y/Ym/d/').date('Ymd').microtime(true).mt_rand().'.jpg';
    public function old_upQiniu($from, $to, $is_up = true)
    {
        $to = 'caiji/weixin/'.date('Y/Ym/d/').date('Ymd').microtime(true).mt_rand().'.jpg';
        if(empty($is_up)){
            return $to;
        }

        // 各种文件与路径
        $from  = str_replace('&amp;', '&', $from);  // 避免获取到的图片不能展示
        $ext   = pathinfo($from, PATHINFO_EXTENSION);
        $ext   = $ext ?: 'jpg';
        $local = dirname(__DIR__).DIRECTORY_SEPARATOR.'image'.DIRECTORY_SEPARATOR.'aa.'.$ext;
        $thumb = dirname(__DIR__).DIRECTORY_SEPARATOR.'image'.DIRECTORY_SEPARATOR.'bb.'.$ext;

        // 将文件保存在本地
        $fileData = file_get_contents($from);
        file_put_contents($local, $fileData);

        // 转移
        $type  = $this->mimeTypes($ext);
        $token = $this->qiniuToken();
        $res   = $this->qiUpload()->putFile($token, $to, $local, null, $type, false);
        $err   = $res[1];
        $ret   = $res[0];
        if($err){
            if(is_string($err)){
                $this->showMsg('       =====>转移图片：'.$to.'失败：'.$err);
            } else{
                var_dump($err);
                $this->showMsg('       =====>转移图片：'.$to.'失败：');
            }
        }

        // 组合域名地址
        $domain = Config::get('site.cdnHost');
        if(substr($domain, -1) != '/'){
            $domain = $domain.'/';
        }

        // 判断七牛云上是否已经存在图片：的缩略图
        // 获取原创的图片
        $image    = $domain.$to.'?imageMogr2/auto-orient/thumbnail/690';
        $to_local = $local.'_thumb.jpg';
        $to_to    = $to.'_thumb.jpg';
        $prefix   = $to_to;
        // 有些图片是打不开的
        try{
            // 将文件保存在本地
            $fileData = file_get_contents($image);
            file_put_contents($thumb, $fileData);
            if(empty($fileData)){
                $this->showMsg('       =====>转移图片：'.$to.' 没有内容！！');
            }

            // 压缩图片
            $to_type = $this->mimeTypes('jpg');
            $result  = $this->compress($thumb, $to_local);
            if($result){
                $this->showMsg('       =====>转移图片：'.$to.' 的缩略图！！');
                $res = $this->qiUpload()->putFile($token, $to_to, $to_local, null, $to_type, false);
            } else{
                $this->showMsg('       =====>转移图片：'.$to.' 的缩略图==压缩图片失败！！');
            }
        } catch(\Exception $e){
            $this->showMsg('转移图片的缩略图打不开：'.$image);
        }

        return $to_to;
        //return $to;
    }


    // 上传图片到七牛云
    public function upQiniu($from, $to)
    {
        // 各种文件与路径
        $ext  = pathinfo($from, PATHINFO_EXTENSION);
        $ext  = $ext ?: 'jpg';
        $type = $this->mimeTypes($ext);

        // 转移
        $token = $this->qiniuToken();
        $res   = $this->qiUpload()->putFile($token, $to, $from, null, $type, false);
        $err   = $res[1];
        $ret   = $res[0];
        if($err){
            $msg = '       =====>转移图片：'.$to.'失败：'.(is_string($err) ? $err : '');

            return $this->return_false($msg);
        }

        return $to;
    }

    // 判断图片是否存在
    public function isExistImage($prefix)
    {
        $qiBucket = $this->qiBucket();
        $bucket   = $this->bucket();
        // 判断七牛云上是否已经存在图片
        //$prefix  = 'UPLOAD/2015/05/01/20150501070530.jpg'; // 要列取文件的公共前缀
        $marker  = ''; // 上次列举返回的位置标记，作为本次列举的起点信息。
        $limit   = 100; // 本次列举的条目数，范围为 1-1000
        $limiter = ''; // 指定目录分隔符，列出所有公共前缀
        $result  = $qiBucket->listFilesv2($bucket, $prefix, $marker, $limit, $limiter, true);
        $files   = $result[0];
        //var_dump($result);

        return $files;
    }


    // 七牛云秘钥认证
    protected function qiAuth()
    {
        if(empty($this->qiniu['auth'])){
            $accessKey = config('filesystems.disks.qiniu.access_key');
            $secretKey = config('filesystems.disks.qiniu.secret_key');
            // 实例化
            $this->qiniu['auth'] = new Auth($accessKey, $secretKey);
        }

        return $this->qiniu['auth'];
    }

    // 七牛云 上传 实例化
    protected function qiUpload()
    {
        if(empty($this->qiniu['qiUpload'])){
            $this->qiniu['qiUpload'] = new UploadManager();
        }

        return $this->qiniu['qiUpload'];
    }

    // 七牛云 实例化
    protected function qiBucket()
    {
        if(empty($this->qiniu['qiBucket'])){
            $auth = $this->qiAuth();
            // 实例化
            $this->qiniu['qiBucket'] = new BucketManager($auth);
        }

        return $this->qiniu['qiBucket'];
    }

    // 七牛 token
    protected function qiniuToken()
    {
        if(empty($this->qiniu['token'])){
            $auth   = $this->qiAuth();
            $bucket = config('filesystems.disks.qiniu.bucket');//上传空间名称
            // 组合token
            $this->qiniu['token'] = $auth->uploadToken($bucket);
        }


        return $this->qiniu['token'];
    }

    // 压缩文件
    protected function compress($file, $toFile)
    {
        // 图片信息
        $splFile  = new \SplFileInfo($file);
        $filePath = $splFile->getPathname();
        // 几张内存不足的图片
        $out = ['UPLOAD/2020/10/26/5f96bbf784808.jpg'];
        if(in_array($file, $out)){
            return false;
        }

        //获取图像信息
        $info = getimagesize($filePath);
        if(empty($info)){
            return $this->return_false('       =====>获取图片信息失败！');
        }

        $type = image_type_to_extension($info[2], false);
        $fun  = "imagecreatefrom{$type}";
        $im   = $fun($filePath);
        if(empty($im)){
            return $this->return_false('       =====>'.$fun.'打开图片失败！');
        }

        // 新图片高与宽
        $width     = $info[0];
        $height    = $info[1];
        $to_width  = 500;
        $to_height = $height * $to_width / $width;

        // 制作等比例图片
        if($width > $to_width){
            //创建新图像
            $x   = $y = 0;
            $img = imagecreatetruecolor($to_width, $to_height);
            imagesavealpha($img, true); //这里很重要 意思是不要丢了$sourePic图像的透明色
            $color = imagecolorallocatealpha($img, 255, 255, 255, 127);
            imagefill($img, 0, 0, $color);
            // 裁剪
            imagecopyresampled($img, $im, 0, 0, $x, $y, $to_width, $to_height, $width, $height);
            imagedestroy($im); //销毁原图
            // 新突破
            $im = $img;
        }

        // 保存图片
        imageinterlace($im, 1);  // 间隔扫描 1-提升质量
        imagejpeg($im, $toFile, 70);  // 图片质量70
        imagedestroy($im);

        return $toFile;
    }

    // 返回失败
    protected function return_false($error)
    {
        $this->error = $error;

        return false;
    }

    // 获取七牛云的桶
    protected function bucket()
    {
        if(empty($this->qiniu['bucket'])){
            $this->qiniu['bucket'] = config('filesystems.disks.qiniu.bucket');//上传空间名称
        }

        return $this->qiniu['bucket'];
    }

    // 文件的类型
    protected function mimeTypes($ext)
    {
        $types = array(
            'txt'  => 'text/plain',
            'htm'  => 'text/html',
            'html' => 'text/html',
            'php'  => 'text/html',
            'css'  => 'text/css',
            'js'   => 'application/javascript',
            'json' => 'application/json',
            'xml'  => 'application/xml',
            'swf'  => 'application/x-shockwave-flash',
            'flv'  => 'video/x-flv',

            // images
            'png'  => 'image/png',
            'jpe'  => 'image/jpeg',
            'jpeg' => 'image/jpeg',
            'jpg'  => 'image/jpeg',
            'gif'  => 'image/gif',
            'bmp'  => 'image/bmp',
            'ico'  => 'image/vnd.microsoft.icon',
            'tiff' => 'image/tiff',
            'tif'  => 'image/tiff',
            'svg'  => 'image/svg+xml',
            'svgz' => 'image/svg+xml',

            // archives
            'zip'  => 'application/zip',
            'rar'  => 'application/x-rar-compressed',
            'exe'  => 'application/x-msdownload',
            'msi'  => 'application/x-msdownload',
            'cab'  => 'application/vnd.ms-cab-compressed',

            // audio/video
            'mp3'  => 'audio/mpeg',
            'qt'   => 'video/quicktime',
            'mov'  => 'video/quicktime',

            // adobe
            'pdf'  => 'application/pdf',
            'psd'  => 'image/vnd.adobe.photoshop',
            'ai'   => 'application/postscript',
            'eps'  => 'application/postscript',
            'ps'   => 'application/postscript',

            // ms office
            'doc'  => 'application/msword',
            'rtf'  => 'application/rtf',
            'xls'  => 'application/vnd.ms-excel',
            'ppt'  => 'application/vnd.ms-powerpoint',

            // open office
            'odt'  => 'application/vnd.oasis.opendocument.text',
            'ods'  => 'application/vnd.oasis.opendocument.spreadsheet',
        );

        return $types[$ext] ?? '';
    }


}


